package com.lyz.file.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
 * 覆盖原来的读行数据的方法，防止出现中文乱码
 * @author luyongzhao
 *
 */
public class RandomAccessFileExt extends RandomAccessFile {

	public RandomAccessFileExt(File file, String mode)
			throws FileNotFoundException {
		super(file, mode);
	}
	
	public final String readLine(String encode) throws IOException{
		
		byte[] bytes = new byte[1024];
		int index = 0;
		int length = 0;
		int c = -1;
		boolean eol = false;

		while (!eol) {
		    switch (c = read()) {
		    case -1:
		    case '\n':
			eol = true;
			break;
		    case '\r':
			eol = true;
			long cur = getFilePointer();
			if ((read()) != '\n') {
			    seek(cur);
			}
			break;
		    default:
		    /*如果超出当前数组长度，则分配多一倍的空间*/
		    if(index >= bytes.length-1){
		    	byte[] dstBytes = new byte[bytes.length*2];
		    	System.arraycopy(bytes, 0, dstBytes, 0, bytes.length);
		    	bytes = dstBytes;
		    }
		    bytes[index] = (byte)(c&0xff);
	    	index++;
	    	length++;
			break;
		    }
		}

		if ((c == -1) && (length == 0)) {
		    return null;
		}
		byte[] bs = new byte[length];
		System.arraycopy(bytes, 0, bs, 0, length);
		return new String(bs,encode);
//		return bs;
	}

}
